package com.jz.community.moduleshopping.groupbuying.ui;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.services.core.PoiItem;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpFragment;
import com.jz.community.basecomm.loaction.LocationManager;
import com.jz.community.basecomm.loaction.PoiManager;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.BaseUserUtils;
import com.jz.community.basecomm.utils.LoggerUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.WXLaunchMiniProgramUtils;
import com.jz.community.basecomm.utils.rxbus.RxBus;
import com.jz.community.basecomm.utils.rxbus.eventType.ToLoginEvent;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.R2;
import com.jz.community.moduleshopping.groupbuying.adapter.GroupBuyingAdapter;
import com.jz.community.moduleshopping.groupbuying.bean.GroupBuyingBean;
import com.jz.community.moduleshopping.groupbuying.task.GroupBuyingTask;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;

import butterknife.BindView;
import io.reactivex.Observable;

public class GroupBuyingFragment extends BaseMvpFragment implements BaseQuickAdapter.RequestLoadMoreListener, OnRefreshListener {

    @BindView(R2.id.rv_group_buying_list)
    RecyclerView rvGroupBuyingList;
    @BindView(R2.id.sr_group_buying_refresh)
    SmartRefreshLayout srGroupBuyingRefresh;
    @BindView(R2.id.rl_group_buying)
    RelativeLayout rlGroupBuying;
    TextView tvGroupBuyingEditAdd;
    TextView tvGroupBuyingAdd;
    RelativeLayout groupEmptyLoginLayout;
    LinearLayout group_near_subject_layout;
    ImageView iv_group_buying_bg;
    private TextView empty_login_tv;
    private TextView empty_login_btn;

    private int page = 0;
    GroupBuyingAdapter groupBuyingAdapter;
    public String mLatitude;
    public String mLongitude;
    public String mCityCode;
    private static final int CODE_GETADD = 0X00001;
    WXLaunchMiniProgramUtils utils;
    private Observable<ToLoginEvent> toLoginRxBusObser;
    private int mDistance;
    private float SHOW_ADV_IMAGE_RADIO = 750.0f / 436.0f;


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.module_shopping_fragment_group_buying;
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }

    @Override
    protected void initVisible() {
        super.initVisible();
        setImmersionBar(false);
    }

    /**
     * 兼容滑动状态栏
     */
    private void setMineUserToolbar(boolean isScollState, int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (isScollState) {
                setImmersionBar(color);
            } else {
                setImmersionBar(color);
            }
        } else {
            if (isScollState) {
                setImmersionBar(R.color.comm_toolbar_color);
            } else {
                setImmersionBar(color);
            }
        }
    }

    @Override
    protected void initView() {
        srGroupBuyingRefresh.setOnRefreshListener(this);//刷新监听
        srGroupBuyingRefresh.setEnableLoadMore(false);
        View headView = LayoutInflater.from(getActivity()).inflate(R.layout.module_shopping_head_group_buying, (ViewGroup) rvGroupBuyingList.getParent(), false);
        groupBuyingAdapter = new GroupBuyingAdapter(R.layout.module_shopping_item_group_buying, new ArrayList<>());
        rvGroupBuyingList.setLayoutManager(new LinearLayoutManager(getActivity()));
        groupBuyingAdapter.setOnLoadMoreListener(this, rvGroupBuyingList);
        tvGroupBuyingEditAdd = headView.findViewById(R.id.tv_group_buying_edit_add);
        tvGroupBuyingAdd = headView.findViewById(R.id.tv_group_buying_add);
        groupEmptyLoginLayout = headView.findViewById(R.id.group_empty_login_layout);
        group_near_subject_layout = headView.findViewById(R.id.group_near_subject_layout);
        empty_login_tv = headView.findViewById(R.id.empty_login_tv);
        empty_login_btn = headView.findViewById(R.id.empty_login_btn);
        iv_group_buying_bg = headView.findViewById(R.id.iv_group_buying_bg);
        setIvBgParams();
        groupBuyingAdapter.setHeaderView(headView);
        rvGroupBuyingList.setAdapter(groupBuyingAdapter);
        utils = new WXLaunchMiniProgramUtils(getActivity());
        registerLoginByRxBus();
    }

    private void setIvBgParams() {
        ViewGroup.LayoutParams params = iv_group_buying_bg.getLayoutParams();
        float advIvRadio = SHOW_ADV_IMAGE_RADIO;
        int advImageHeight = (int) (SHelper.getScrrenW(getActivity()) / advIvRadio);
        params.height = advImageHeight;
        iv_group_buying_bg.setLayoutParams(params);
    }

    @Override
    protected void initDatas() {
        beginLocation();
    }

    private void registerLoginByRxBus() {
        toLoginRxBusObser = RxBus.getInstance().register(ToLoginEvent.toLoginRxBusTag, ToLoginEvent.class);
        toLoginRxBusObser.subscribe(toLoginEvent -> handleLoginState(toLoginEvent), throwable -> {
        });
    }

    private void handleLoginState(ToLoginEvent toLoginEvent) {
        if (toLoginEvent.isToPwdLogin() || toLoginEvent.isToWeChatLogin()) {
            SHelper.gone(groupEmptyLoginLayout);
            beginLocation();
        } else {
            SHelper.vis(groupEmptyLoginLayout);
            groupBuyingAdapter.getData().clear();
            groupBuyingAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void addListener() {

        tvGroupBuyingEditAdd.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), EditAddressActivity.class);
            startActivityForResult(intent, CODE_GETADD);
        });

        empty_login_btn.setOnClickListener(v -> {
            RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.MODULE_AUTHORIZATION_LOGIN);
        });

        groupBuyingAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (BaseSpUtils.getInstance().getIsLogin(getActivity())) {
                String path = "/pages/groupTransmit/solitaireDetail/solitaireDetail?"
                        + "cityId=" + groupBuyingAdapter.getData().get(position).getCityCode()
                        + "&groupId=" + groupBuyingAdapter.getData().get(position).getId()
                        + "&shareId=" + BaseSpUtils.getInstance().getUserId(getActivity());
                if (!TextUtils.isEmpty(BaseSpUtils.getInstance().getOpenid(getActivity()))) {
                    path = path + "&userUnionId=" + BaseSpUtils.getInstance().getWxUd(getActivity());
                    path = path + "&nickName=" + BaseSpUtils.getInstance().getNickname(getActivity());
                    path = path + "&token=" + BaseSpUtils.getInstance().getAccess_token(getActivity());
                } else {
                    path = path + "&token=" + BaseSpUtils.getInstance().getAccess_token(getActivity());
                    path = path + "&username=" + BaseSpUtils.getInstance().getUserId(getActivity());
                }
                utils.launchMiniProgram(path);
            } else {
                BaseUserUtils.showIsLoginDialog(getActivity());
            }
        });

        rvGroupBuyingList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                mDistance += dy;
            }
        });
    }

    private void beginLocation() {
        LocationManager lm = new LocationManager();
        lm.getLocation(result -> {
            if (result.mResultId == 0) {
                mLatitude = result.mLocation.mLatitude + "";
                mLongitude = result.mLocation.mLongitude + "";
                mCityCode = result.mLocation.mCityCode;
                lnToCommunity(result.mLocation.mLatitude, result.mLocation.mLongitude, mCityCode);
                if (BaseSpUtils.getInstance().getIsLogin(getActivity())) {
                    SHelper.gone(groupEmptyLoginLayout);
                    getData(mLatitude, mLongitude, mCityCode, 0);
                } else {
                    SHelper.vis(groupEmptyLoginLayout);
                }
            } else {
                tvGroupBuyingAdd.setText("定位失败");
            }
        }, getActivity());
    }


    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        getData(mLatitude, mLongitude, mCityCode, 0);
    }

    @Override
    public void onLoadMoreRequested() {
        getData(mLatitude, mLongitude, mCityCode, 1);
    }


    public void refreshData() {
        getData(mLatitude, mLongitude, mCityCode, 0);
    }


    private void getData(String mLatitude, String mLongitude, String cityCode, int type) {
        srGroupBuyingRefresh.finishRefresh();
        if (type == 0) {
            page = 0;
        } else {
            page++;
        }
        new GroupBuyingTask(getActivity(), o -> {
            if (!Preconditions.isNullOrEmpty(o)) {
                GroupBuyingBean bean = (GroupBuyingBean) o;
                if (!Preconditions.isNullOrEmpty(bean.get_embedded()) && !Preconditions.isNullOrEmpty(bean.get_embedded().getContent())) {
                    SHelper.gone(groupEmptyLoginLayout);
                    SHelper.vis(group_near_subject_layout);
                    if (type == 0) {
                        groupBuyingAdapter.setNewData(bean.get_embedded().getContent());
                    } else {
                        groupBuyingAdapter.addData(bean.get_embedded().getContent());
                        groupBuyingAdapter.loadMoreComplete();
                    }
                } else {
                    if (type != 0) {
                        groupBuyingAdapter.loadMoreEnd();
                    } else {
                        groupBuyingAdapter.getData().clear();
                        groupBuyingAdapter.notifyDataSetChanged();
                    }
                    notData();
                }
            } else {
                if (type == 0) {
                    groupBuyingAdapter.getData().clear();
                    groupBuyingAdapter.notifyDataSetChanged();
                } else {
                    groupBuyingAdapter.loadMoreEnd();
                }
                notData();
            }
        }).execute(page + "", mLatitude, mLongitude, cityCode);
    }

    private void notData() {
        if (page == 0) {
            SHelper.vis(groupEmptyLoginLayout, empty_login_tv);
            SHelper.gone(empty_login_btn, group_near_subject_layout);
            empty_login_tv.setText("暂无拼团...");
        }
    }

    private void lnToCommunity(final double lat, final double lon, String cityCode) {
        new PoiManager(getActivity(), lat, lon, "", true, list -> {
            if (!Preconditions.isNullOrEmpty(list)) {
                SpannableString aTitle = new SpannableString(list.get(0).getTitle());
                SpannableString aAddress = new SpannableString(list.get(0).getProvinceName() + list.get(0).getCityName() + list.get(0).getAdName() + list.get(0).getSnippet());
                StyleSpan styleSpan_B = new StyleSpan(Typeface.BOLD);
                aTitle.setSpan(styleSpan_B, 0, aTitle.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                SpannableStringBuilder builder = new SpannableStringBuilder();
                builder.append(aTitle)
                        .append("   ")
                        .append(aAddress);
                tvGroupBuyingAdd.setText(builder);
            } else {
                tvGroupBuyingAdd.setText("定位失败");
            }
        }, cityCode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_GETADD && resultCode == RESULT_OK) {
            PoiItem poiItem = data.getParcelableExtra("address");
            SpannableString aTitle = new SpannableString(poiItem.getTitle());
            SpannableString aAddress = new SpannableString(poiItem.getProvinceName() + poiItem.getCityName() + poiItem.getAdName() + poiItem.getSnippet());
            StyleSpan styleSpan_B = new StyleSpan(Typeface.BOLD);
            aTitle.setSpan(styleSpan_B, 0, aTitle.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append(aTitle)
                    .append("   ")
                    .append(aAddress);
            tvGroupBuyingAdd.setText(builder);
            mLatitude = poiItem.getLatLonPoint().getLatitude() + "";
            mLongitude = poiItem.getLatLonPoint().getLongitude() + "";
            getData(mLatitude, mLongitude, mCityCode, 0);
        }
    }

    private void unregisterLoginByRxBus() {
        RxBus.getInstance().unregister(ToLoginEvent.toLoginRxBusTag, toLoginRxBusObser);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterLoginByRxBus();
    }
}
